package com.lwc.cfdns.utils.ip;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lwc.cfdns.utils.StringUtils;
import com.lwc.cfdns.utils.http.HttpUtils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 根据IP获取地址类
 *
 * @author luwc
 * @version 1.0.0
 * @return null
 * @throws
 * @time 2023/5/19 15:23:35
 */
public class AddressUtils {
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);
    // IP地址查询
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
    // 未知地址
    public static final String UNKNOWN = "XX XX";

    public static String getRealAddressByIP(String ip) {
        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        try {
            String rspStr = HttpUtils.sendGet(IP_URL, "ip=" + ip + "&json=true", "GBK");
            if (StringUtils.isEmpty(rspStr)) {
                log.error("获取地理位置异常 {}", ip);
                return UNKNOWN;
            }
            ObjectMapper objectMapper = new ObjectMapper();
            IpJson obj = objectMapper.readValue(rspStr, IpJson.class);
            String region = obj.getPro();
            String city = obj.getCity();
            return String.format("%s %s %s", region, city, obj.getRegion());
        } catch (Exception e) {
            log.error("获取地理位置异常 {}", ip);
        }
        return UNKNOWN;
    }
}

/**
 * 返回的实例
 *
 * @author luwc
 * @version 1.0.0
 * @throws
 * @time 2023/5/19 15:21:40
 */
@Data
class IpJson {
    // {"ip":"222.222.38.4","pro":"河北省","proCode":"130000","city":"石家庄市","cityCode":"130100","region":"","regionCode":"0","addr":"河北省石家庄市 电信","regionNames":"","err":""}
    private String ip;
    private String pro;// 河北省
    private String proCode;
    private String city;
    private String cityCode;
    private String region;
    private String regionCode;
    private String addr;
    private String regionNames;
    private String err;
}